package cn.da.shuai.cool.system.service.service.impl;

import cn.da.shuai.cool.mybatis.enums.DataScopeType;
import cn.da.shuai.cool.mybatis.service.ICoolDataAuthService;
import cn.da.shuai.cool.system.service.domain.CoolUserDetails;
import cn.da.shuai.cool.system.service.mapper.CoolDataAuthMapper;
import cn.da.shuai.cool.system.model.entity.user.CoolUser;
import cn.da.shuai.cool.security.util.SecurityUtil;
import cn.da.shuai.cool.system.service.service.ICoolUserService;
import cn.hutool.core.util.ArrayUtil;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CoolDataAuthServiceImpl implements ICoolDataAuthService {

    public final CoolDataAuthMapper dataAuthMapper;

    public final ICoolUserService userService;

    @Lazy
    public CoolDataAuthServiceImpl(CoolDataAuthMapper dataAuthMapper, ICoolUserService userService) {
        this.dataAuthMapper = dataAuthMapper;
        this.userService = userService;
    }

    @Override
    public List<Integer> getUserIdsByDataScope(DataScopeType... dataScopeTypes) {

        if (ArrayUtil.isEmpty(dataScopeTypes)) {
            return List.of();
        }

        CoolUserDetails currentUser = (CoolUserDetails) SecurityUtil.getCurrentUser();
        if (currentUser == null) {
            return List.of();
        }
        List<Integer> userIds = new ArrayList<>(32);
        CoolUser coolUser = currentUser.getCoolUser();
        for (DataScopeType type : dataScopeTypes) {
            switch (type) {
                case SELF -> userIds.add(coolUser.getId());
                // 获取当前部门及其子部门的权限
                case DEPT -> userIds.addAll(userService.getUserIdsByDept(coolUser.getId()));
                // 获取当前用户的岗位相关人员
                case POST -> userIds.addAll(userService.getUserIdsByRole(coolUser.getId()));
                // 获取当前用户的角色相关人员
                case ROLE -> userIds.addAll(userService.getUserIdsByPosition(coolUser.getId()));
            }
        }

        return userIds;
    }
}
